package cn.johnyu.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@CrossOrigin
@RestController
@RequestMapping("/sse")
public class ChatController {

    @GetMapping("/chat")
    public SseEmitter chat(HttpServletResponse response) {
        response.setContentType("text/event-stream;charset=UTF-8");
        SseEmitter emitter = new SseEmitter(0L); // 永不超时

        Executors.newSingleThreadExecutor().submit(() -> {
            try {
                String[] messages = {
                        "您好，我是智能客服，请问有什么可以帮您？",
                        "我可以帮您查订单、退货、人工转接等服务。",
                        "如果需要人工服务，请回复“转接”。"
                };

                for (String msg : messages) {
                    emitter.send(SseEmitter.event().data(msg));
                    TimeUnit.SECONDS.sleep(2); // 模拟打字效果
                }

                emitter.send(SseEmitter.event().data("[结束]"));
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }

    @GetMapping("/chat2")
    public SseEmitter chat2(HttpServletResponse response) {
        response.setContentType("text/event-stream;charset=UTF-8");
        SseEmitter emitter = new SseEmitter(0L); // 永不超时

        Executors.newSingleThreadExecutor().submit(() -> {
            try {
                String message = "您好，我是智能客服，请问有什么可以帮您？我可以帮您查订单、退货、人工转接等服务。如果需要人工服务，请回复“转接”。";

                for (char ch : message.toCharArray()) {
                    emitter.send(SseEmitter.event().data(String.valueOf(ch)));
                    Thread.sleep(100); // 控制打字速度，100ms一个字
                }

                emitter.send(SseEmitter.event().data("\n[结束]"));
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }
}